from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from staff.models import *
from staff.serializer import *
from .models import *
import redis,json,jwt,re,os,random,datetime
from .serializer import *
from rest_framework.viewsets import ModelViewSet
from rest_framework.viewsets import ViewSet
from utils.ip_address.ip_info import CzIp
from rest_framework.pagination import PageNumberPagination


# 分页的视图
class MyPagination(PageNumberPagination):

    page_size = 1
    max_page_size = 5

    page_query_param = "size"
    page_size_query_param = "pagesize"


# 统计省份人数，生日月份人数，员工数据
class StaffCountView(APIView):
    def get(self,request):
        # 员工总数
        total = StaffModel.objects.all().count()
        # 实习生总数
        # 在职位表中  查询实习生的职位id
        position = PositionModel.objects.filter(name = "实习生")
        staff_exercitation_num = 0
        for i in position:
            num = StaffModel.objects.filter(position_id=i.id).count()
            staff_exercitation_num+=num
        # 正式员工人数
        staff_formal_num = total-staff_exercitation_num
        # 地区人数
        regional_distribution={}
        birthday = {}
        staffs = StaffModel.objects.all()
        # 循环遍历所有员工
        for i in staffs:
            region = i.region
            month = str(i.birthday).split('-')[1]
            # 循环将1-12个月加入到字段中
            for c in range(1,13):
                c=str(c)
                if c not in birthday.keys():
                    count = 0
                    birthday.update({c: count})
                # 如果员工的生日月份对应字典中的key值，则这个月份出生的人数+1
                if int(month) == int(c):
                    birthday[c]=birthday[c]+1

            if region not in regional_distribution.keys():
                count=1
                regional_distribution.update({region:count})
            else:
                regional_distribution[region]=regional_distribution[region]+1

        return Response({"code":status.HTTP_200_OK,
                         "msg":"获取人数成功",
                         "total":total,
                         "staff_exercitation_num":staff_exercitation_num,
                         "staff_formal_num":staff_formal_num,
                         "regional_distribution":regional_distribution,
                         "birthday":birthday})


# 获取所有角色信息
class RoleModelAPIView(ModelViewSet):
    queryset = RoleModel.objects.filter(is_delete=False).all()
    serializer_class = RoleSer
    pagination_class = MyPagination
    cz = CzIp()

    # 获取所有角色数据信息
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    # 添加角色信息
    def create(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        # print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get("name")
        desc = request.data.get("desc")
        try:
            if RoleModel.objects.filter(name=name).first():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": "角色已存在"
                })
            # RoleModel.objects.create(name=name, desc=desc)
            role_data = {
                "name": name,
                "desc": desc
            }
            role_ser = RoleSer(data=role_data)
            if not role_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": role_ser.errors
                })
            role_ser.save()
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="添加角色操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加角色成功"
            })
        except Exception as e:
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误！{e}"
            })


# 删除角色
class DropRole(ViewSet):
    cz = CzIp()
    def delete(self,request, pk):
        try:
            staff = request.session.get("staff")
            print('token_id', staff)
            staff_id = staff.get('id')
            RoleModel.objects.filter(id=pk).update(is_delete=True)
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="删除角色操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message":"删除角色成功！",
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 修改角色
    def update(self,request,pk):
        staff = request.session.get("staff")
        # print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get("name")
        desc = request.data.get("desc")

        role = RoleModel.objects.filter(id=pk,is_delete=False)
        if role:
            if name:
                role.update(name=name)
            if desc:
                role.update(desc=desc)
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="修改角色操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改角色成功！"
            })
        else:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "修改失败！"
            })


# 搜索角色数据
class SearchRoleAPIView(APIView):
    def get(self, request):
        name = request.data.get('name')
        print('asda?>>>', name)
        role = RoleModel.objects.filter(name__contains=name, is_delete=False).all()
        role_ser = RoleSer(role, many=True).data
        print('123>>>', role)
        return Response({
            'code': status.HTTP_200_OK,
            "message": "查询成功!",
            "role_list": role_ser
        })


# 递归获取数据
def recursion_data(lst):
    if len(lst) == 0:
        return []
    for i in lst:
        id = i.get("id")
        menu = MenuModel.objects.filter(menu_id=id, is_delete=False).order_by("order").all()
        menu = MenuSer(menu, many=True)
        menu = json.loads(json.dumps(menu.data))
        i["menu_list"] = recursion_data(menu)
    return lst


# 获取员工菜单信息
class StaffMenuSet(ModelViewSet):
    queryset = MenuModel.objects.filter(is_delete=False).all()
    serializer_class = MenuSer

    def list(self, request, *args, **kwargs):
        try:
            staff = request.session.get("staff")
            print('token_id', staff)
            id = staff.get('id')
            print("id>>>", id)
            staff = StaffModel.objects.filter(id=id, is_delete=False).first()
            print('staFFF???>>>>', staff.position_id)
            position_role = Role_MenuModel.objects.filter(role_id=staff.role_id, is_delete=False).all()
            print('2312>>>>', position_role)
            menu_queryset = MenuModel.objects.filter(menu_id=None, is_delete=False).order_by("order").all()
            menu_list = []
            for i in position_role:
                print("idddddddd", i.role_id)
                menu = menu_queryset.filter(id=i.menu_id).order_by("order").all()
                print('sdfghjk>>>>>>>>>>>>>>>>>>>>>>>>>>', menu)
                menu = MenuSer(menu, many=True)
                menu = json.loads(json.dumps(menu.data))
                menu = recursion_data(menu)
                menu_list.extend(menu)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取成功！",
                "list": menu_list
            })
        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误！{e}",
            })


# 获取所有菜单信息
class MenuSet(ModelViewSet):
    queryset = MenuModel.objects.filter(is_delete=False).all()
    serializer_class = MenuSer
    cz = CzIp()

    # 获取所有菜单
    def list(self, request, *args, **kwargs):
        try:
            menu = MenuModel.objects.filter(menu_id=None,is_delete=False).order_by("order").all()
            menu = MenuSer(menu, many=True)
            menu = json.loads(json.dumps(menu.data))
            menu_list = recursion_data(menu) # 递归获取子目录
            return Response({"code": status.HTTP_200_OK, "message": "ok！", "menu_list": menu_list})
        except Exception as e:
            print("错误信息", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "message": f"服务器错误！{e}"})

    # 添加菜单
    def create(self, request, *args, **kwargs):
        try:
            staff = request.session.get("staff")
            print('token_id', staff)
            staff_id = staff.get('id')
            menu_id = request.data.get("menu_id")
            name = request.data.get("name")
            order = request.data.get("order")
            path = request.data.get("path")
            icon = request.data.get("icon")

            menu_name = MenuModel.objects.filter(name=name).first()
            if menu_name:
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": "菜单已存在!"
                })
            menu_data = {
                "menu_id": menu_id,
                "name": name,
                "order": order,
                "path": path,
                "icon": icon,
            }
            print(menu_data)
            menu_ser = MenuSer(data=menu_data)
            if not menu_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": menu_ser.errors
                })
            menu_ser.save()

            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="添加菜单操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加菜单成功！"
            })

        except Exception as e:
            print("错误>>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 删除菜单
class DropMenu(ViewSet):
    cz = CzIp()

    def delete(self, request, pk):
        try:
            staff = request.session.get("staff")
            # print('token_id', staff)
            staff_id = staff.get('id')
            MenuModel.objects.filter(id=pk).update(is_delete=True)
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="删除菜单操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "删除菜单成功!"
            })
        except Exception as e:
            print("错误>>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 修改菜单
    def update(self,request,pk):
        staff = request.session.get("staff")
        # print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get('name')
        path = request.data.get('path')
        icon = request.data.get('icon')
        order = request.data.get('order')
        menu_id = request.data.get('menu_id')

        menu = MenuModel.objects.filter(id=pk, is_delete=False)
        if menu:
            if name:
                menu.update(name=name)
            if path:
                menu.update(path=path)
            if icon:
                menu.update(icon=icon)
            if order:
                menu.update(order=order)
            if menu_id:
                menu.update(menu_id=menu_id)

            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="修改菜单操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,address=address,facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改菜单成功！"
            })
        else:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "错误！"
            })


# 搜索菜单
class SearchMenu(APIView):
    def get(self,request):
        name = request.data.get("name")
        print('name>>>', name)
        menu = MenuModel.objects.filter(name__contains=name, is_delete=False).all()
        menu_ser = RoleSer(menu, many=True).data
        print('munr', menu)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "搜索菜单成功!",
            "menu": menu_ser
        })


# 获取部门信息
class DepartmentView(ModelViewSet):
    queryset = DepartmentModel.objects.all()
    serializer_class = DepartmentSer
    cz = CzIp()

    def list(self, request, *args, **kwargs):
        demp = DepartmentModel.objects.filter(is_delete=False).all()
        demp_ser = DepartmentSer(demp, many=True)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取部门数据成功!",
            "dep_list": demp_ser.data
        })

    # 添加部门
    def create(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        staff_id = staff.get('id')
        name = request.data.get("name")
        depar = DepartmentModel.objects.filter(name=name).first()
        print("布恩》》》", depar)
        if depar:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "部门已存在"
            })

        ser = DepartmentSer(data=request.data)
        if not ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": ser.errors
            })

        ser.save()

        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="添加部门操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "添加部门成功！"
        })


# 删除部门
class DropDepartment(ViewSet):
    cz = CzIp()

    def delete(self,request, pk):
        try:
            staff = request.session.get("staff")
            staff_id = staff.get('id')
            DepartmentModel.objects.filter(id=pk).update(is_delete=True)
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="删除部门操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "删除部门成功！"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 修改部门
    def update(self, request, pk):
        staff = request.session.get("staff")
        staff_id_id = staff.get('id')
        name = request.data.get("name")
        desc = request.data.get("desc")
        staff_id = request.data.get("staff_id")
        department_id = request.data.get("department_id")

        depar = DepartmentModel.objects.filter(id=pk, is_delete=False)
        if not depar:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "部门不存在"
            })
        if name:
            depar.update(name=name)
        if desc:
            depar.update(desc=desc)
        if staff_id:
            depar.update(staff_id=staff_id)
        if department_id:
            depar.update(department_id=department_id)

        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="修改部门操作", staff_id=staff_id_id, path=f"{method} {path}", ip=ip, address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message":"修改部门成功！"
        })


# 搜索部门
class SearchDepartment(APIView):
    # cz = CzIp()
    def get(self,request):
        name = request.data.get("name")
        print('name>>>', name)
        depar = DepartmentModel.objects.filter(name__contains=name, is_delete=False).all()
        print('munr', depar)
        depar_ser = DepartmentSer(depar, many=True).data
        depar_ser = json.loads(json.dumps(depar_ser))

        return Response({
            "code": status.HTTP_200_OK,
            "message": "搜索部门成功!",
            "menu": depar_ser
        })


# 职级视图集
class RankSet(ModelViewSet):
    cz = CzIp()
    queryset = RankModel.objects.filter(is_delete=False).all()
    serializer_class = RankSer
    pagination_class = MyPagination

    # 添加职级
    def create(self, request, *args, **kwargs):
        try:
            staff = request.session.get("staff")
            print('token_id', staff)
            staff_id = staff.get('id')
            name = request.data.get("name")
            desc = request.data.get("desc")
            rank_name = RankModel.objects.filter(name=name).first()
            if rank_name:
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": "职级已存在！"
                })
            if len(desc) == 0:
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": "职级描述不能为空！"
                })
            rank_data = {
                'name': name,
                "desc": desc
            }
            rank_ser = RankSer(data=rank_data)
            if not rank_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": rank_ser.errors
                })
            rank_ser.save()

            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="添加职级操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加职级成功！"
            })

        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 删除职级
class DropRank(ViewSet):
    cz = CzIp()
    #
    def delete(self,request,pk):
        staff = request.session.get("staff")
        print('token_id', staff)
        staff_id = staff.get('id')
        RankModel.objects.filter(id=pk).update(is_delete=True)

        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="删除职级操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)

        return Response({
            "code": status.HTTP_200_OK,
            "message": "删除职级成功！"
        })

    # 修改职级
    def update(self,request, pk):
        staff = request.session.get("staff")
        # print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get("name")
        desc = request.data.get("desc")

        rank = RankModel.objects.filter(id=pk,is_delete=False)
        if rank:
            if name:
                rank.update(name=name)
            if desc:
                rank.update(desc=desc)
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="修改职级操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改职级成功！"
            })
        else:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "修改失败！"
            })


# 职位的视图集
class PositionSet(ModelViewSet):
    cz = CzIp()
    queryset = PositionModel.objects.filter(is_delete=False).all()
    serializer_class = PositionSer
    pagination_class = MyPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    # 添加职位
    def create(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get("name")
        rank_id = request.data.get("rank_id")
        department_id = request.data.get("department_id")
        desc = request.data.get("desc")
        print('desc', desc)

        position_name = PositionModel.objects.filter(name=name).first()
        if position_name:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "该职位已存在！"
            })

        position_data = {
            "name": name,
            "rank_id": rank_id,
            "department_id": department_id,
            "desc": desc,
        }
        position_ser = PositionSer(data=position_data)
        if not position_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": position_ser.errors
            })
        # 保存
        position_ser.save()
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="添加职位操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "添加职位成功！"
        })


# 删除职位
class DropPosition(ViewSet):
    cz = CzIp()

    def delete(self,request,pk):
        staff = request.session.get("staff")
        # print('token_id', staff)
        staff_id = staff.get('id')

        PositionModel.objects.filter(id=pk).update(is_delete=True)

        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="删除职位操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "删除职位成功!"
        })

    # 修改职位
    def update(self, request, pk):
        staff = request.session.get("staff")
        # print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get("name")
        rank_id = request.data.get("rank_id")
        department_id = request.data.get("department_id")
        desc = request.data.get("desc")

        position = PositionModel.objects.filter(id=pk, is_delete=False)

        if position:
            if name:
                position.update(name=name)
            if desc:
                position.update(desc=desc)
            if rank_id:
                position.update(rank_id=rank_id)
            if department_id:
                position.update(department_id=department_id)
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="修改职位操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改职位成功！"
            })
        else:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "修改失败！"
            })


# 日志接口
class LogManage(ModelViewSet):
    queryset = Operate_LogModel.objects.filter(is_delete=False).all()
    serializer_class = OperateLogSer
    pagination_class = MyPagination


# 工资条
class PayrollSet(ModelViewSet):
    queryset = PayrollModel.objects.filter(is_delete=False).all()
    serializer_class = PayrollSer
    pagination_class = MyPagination

    cz = CzIp()

    # 添加工资条
    def create(self, request, *args, **kwargs):
        try:
            staff = request.session.get("staff")
            print('token_id', staff)
            staff_id = staff.get('id')
            ser = PayrollSer(data=request.data)
            if not ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": ser.errors
                })
            ser.save()
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="添加工资条操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加成功"
            })
        except Exception as e:
            print('错误>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"添加失败{e}"
            })


# 修改工资条
class PayrollView(APIView):
    cz = CzIp()
    def put(self, request, pk):
        staff_id = request.data.get("staff_id")
        attendance = request.data.get("attendance")
        absenteeism = request.data.get("absenteeism")
        leave = request.data.get("leave")
        base_salary = request.data.get("base_salary")
        position_salary = request.data.get("position_salary")
        # print('asdasdas')
        payroll = PayrollModel.objects.filter(id=pk, is_delete=False).first()
        # print('asdsadasdasdasdasdas======================', payroll)
        payroll_data = PayrollSer(payroll).data
        payroll_data = json.loads(json.dumps(payroll_data))
        # print("lll", payroll_data)

        if staff_id != None:
            # print('asdsd')
            payroll_data['staff_id'] = staff_id
        if attendance != None:
            # print('123')
            payroll_data['attendance'] = attendance
        if absenteeism != None:
            # print("456")
            payroll_data['absenteeism'] = absenteeism
        if leave != None:
            # print("78")
            payroll_data['leave'] = leave
        if base_salary !=None:
            # print("4")
            payroll_data['base_salary'] = base_salary
        if position_salary != None:
            # print("78454")
            payroll_data['position_salary'] = position_salary

        ser = PayrollSer(instance=payroll,data=payroll_data)
        # print("asdd++++++++++++++++++++++++++++")
        if not ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": ser.errors
            })
        ser.save()
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="修改工资条操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "修改成功！"
        })


# 删除工资条
class DropPayroll(APIView):
    cz = CzIp()

    def delete(self, request, pk):
        staff = request.session.get("staff")
        print('token_id', staff)
        staff_id = staff.get('id')
        PayrollModel.objects.filter(id=pk, is_delete=False).update(is_delete=True)
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="删除工资条操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "删除工资条成功！"
        })


# 材料的视图
class MaterialsSet(ModelViewSet):
    queryset = MaterialsModel.objects.all()
    serializer_class = MaterialsSer

    # 获取所有材料信息
    def list(self, request, *args, **kwargs):
        mater = MaterialsModel.objects.filter(is_delete=False).all()
        mater_ser = MaterialsSer(mater, many=True).data
        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取所有材料成功！",
            "results": mater_ser
        })

    # 添加材料
    def create(self, request, *args, **kwargs):
        mater_ser = MaterialsSer(data=request.data)
        if not mater_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                'message': mater_ser.errors
            })
        mater_ser.save()
        return Response({
            "code": status.HTTP_200_OK,
            "message": "添加材料成功"
        })


# 材料管理
class MaterialsAPIView(APIView):
    # 删除材料
    def delete(self, request, pk):
        MaterialsModel.objects.filter(id=pk, is_delete=False).update(is_delete=True)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "删除材料成功！"
        })